package com.naxiang.cn.uploadxinvideo;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Toast;

import com.baidu.cloud.bdrtmpsession.BDRtmpSessionBasic;
import com.naxiang.cn.config.LiveConfig;
import com.naxiang.cn.config.ProcessConfig;
import com.naxiang.cn.listener.ProcessStateListener;
import com.naxiang.cn.session.LiveCaptureSession;
import com.naxiang.cn.session.LiveStreamSession;
import com.naxiang.cn.session.MediaProcessSession;
import com.naxiang.cn.utils.BitmapUtils;
import com.naxiang.cn.utils.CompletedView;
import com.naxiang.cn.utils.FileUtils;
import com.naxiang.cn.utils.NetUtils;
import com.naxiang.cn.utils.ToastMake;
import com.naxiang.cn.widget.BDCloudVideoView.PlayerState;
import com.baidu.cloud.media.player.IMediaPlayer;
import com.bumptech.glide.Glide;
import com.naxiang.cn.utils.ItemBeen;
import com.naxiang.cn.widget.BDCloudVideoView;
import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import okhttp3.Call;
import okhttp3.OkHttpClient;

import static android.app.Activity.RESULT_OK;

/**
 * 作者: 赵航
 * 创建时间: 2018/7/22 16:36
 * 描述:
 */
public class UpLoadActivity extends UZModule implements IMediaPlayer.OnErrorListener, IMediaPlayer.OnInfoListener, IMediaPlayer.OnBufferingUpdateListener, BDCloudVideoView.OnPlayerStateListener {
    //播放器的
    private RelativeLayout mRela;
    private BDCloudVideoView mVV = null;
    private String mUri;


    private boolean isFull     = false;//是否全屏显示
    private boolean mFllScreen = false;//视频比例和屏幕比例不一致的话，默认不能全屏问题
    private boolean mIsStoped  = false;//由暂停转为开始
    private int                   mMaxProbeTime;
    private SimpleMediaController mMediaController;
    private UZModuleContext       mModuleContext;
    private int mLift  = 0; //小屏播放的距离左边的距离
    private int mTop   = 0;//小屏播放的距离上边的距离
    private int mHight = 100;//小屏播放的播放器高度的距离
    private int mWidth = -1;//小屏播放的播放器高度的宽度
    private boolean mFixed; //小屏是否跟着一起滑动
    private String  mIndexName;//小屏可以加载的布局

    //全屏显示的界面以及是否一起滚动
    private boolean mFllFixed;  //大屏是否跟着一起滚动
    private String  mIndexFullName;//大屏索要加载的布局名称

    private boolean isMusic   = false;
    private boolean fullImage = false; //是否点击视频前加载的图片了,全局只显示一次

    private String  mImageUri  = "";
    //标记侧面是否滑出来
    private boolean mCloseOpen = false;
    private ObjectAnimator mAnimtion;
    private JSONArray      mVidoeUriList;
    private JSONArray      mImageUriList;
    private List<ItemBeen> itemBeens        = new ArrayList<>();
    private int            mListImageWidth  = 300;
    private int            mListImageHeight = 500;
    private JSONArray mIdList;
    private String mPeoploNumber = "999人在线";
    private int    mId           = -1;
    private String    mTitleText;
    private String    mHandImageUri;
    private JSONArray mTitleTextList;
    private JSONArray mHandImageUriList;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mHandler.removeCallbacksAndMessages(null);
                    break;
                case 2:
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();

                    JSONObject object = new JSONObject();
                    try {
                        object.put("currentposition", currentPosition);
                        object.put("duration", duration);
                        object.put("mId", mId);
                        if (isFull) {
                            object.put("mIsFull", 1);
                        } else {
                            object.put("mIsFull", 2);
                        }
                        //设置为false为不间断的想后台发送数据
                        mModuleContext.success(object, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    if (currentPosition > 0 && duration > 0) {
                        long pos = 10000L * currentPosition / duration;
                        mMediaController.seatProgress((int) pos);
                        mMediaController.getSeekBar().setEnabled(true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mMediaController.getReadTime().setText(formatMilliSecond(mVV.getCurrentPosition()));
                                mMediaController.getAllTime().setText(formatMilliSecond(mVV.getDuration()));
                            }
                        });

                    } else {
                        mMediaController.getSeekBar().setEnabled(false);


                    }
                    break;
            }
        }
    };



    public UpLoadActivity(UZWebView webView) {
        super(webView);
    }

    //TODO：播放器的植入
    public void jsmethod_openVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;

        //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        mTitleTextList = moduleContext.optJSONArray("titleTextList");
        mHandImageUriList = moduleContext.optJSONArray("handImageUriList");

        mIdList = moduleContext.optJSONArray("idList");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        been.setId((String) mIdList.get(i));
                        been.setHandText((String) mTitleTextList.get(i));
                        been.setHandImage((String) mHandImageUriList.get(i));
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = false;

        mLift = moduleContext.optInt("lift", 0);

        mTop = moduleContext.optInt("top", 0);
        mHight = moduleContext.optInt("hight", 100);
        mWidth = moduleContext.optInt("width", -1);
        mId = moduleContext.optInt("mId", -1);
        //视频是否随着界面一起滚动
        mFixed = moduleContext.optBoolean("fixed", false);
        //视频比例和屏幕比例不一致的话，默认不进行满屏显示
        mFllScreen = moduleContext.optBoolean("fullScreen", false);

        mIndexName = moduleContext.optString("indexName", "");

        mImageUri = moduleContext.optString("imageuri", "");
        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");
        mListImageWidth = moduleContext.optInt("listImagewidth", 300);
        mListImageHeight = moduleContext.optInt("listImageheight", 500);

        mTitleText = moduleContext.optString("titleText", "标题获取失败");
        mHandImageUri = moduleContext.optString("handImageUri", "");


        //切换大屏时，要不要跟着屏幕一起滑动
        mFllFixed = moduleContext.optBoolean("fixedFull", true);
        //切换大屏的时候要添加到那个布局上
        mIndexFullName = moduleContext.optString("indexFullName", "");


        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());
            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            mRela.setBackgroundColor(Color.BLACK);
            removeViewFromCurWindow(mRela);
        }

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mWidth, mHight);
        params.setMargins(mLift, mTop, 0, 0);
        insertViewToCurWindow(mRela, params, mIndexName, mFixed);
        initViodView();
    }

    //打开全屏了
    public void jsmethod_openFullVido(UZModuleContext moduleContext) {
        mModuleContext = moduleContext;
        //TODO:初始化ListVIew数据
        mVidoeUriList = moduleContext.optJSONArray("listvoiduri");
        mImageUriList = moduleContext.optJSONArray("listimageuri");
        mTitleTextList = moduleContext.optJSONArray("titleTextList");
        mHandImageUriList = moduleContext.optJSONArray("handImageUriList");


        mIdList = moduleContext.optJSONArray("idList");
        itemBeens.clear();
        if (mImageUriList != null || mImageUriList.length() != 0) {
            for (int i = 0; i < mImageUriList.length(); i++) {
                if (i < mVidoeUriList.length()) {
                    try {
                        ItemBeen been = new ItemBeen();
                        been.setImageUri((String) mImageUriList.get(i));
                        been.setVidoUri((String) mVidoeUriList.get(i));
                        been.setId((String) mIdList.get(i));
                        been.setHandText((String) mTitleTextList.get(i));
                        been.setHandImage((String) mHandImageUriList.get(i));
                        itemBeens.add(been);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        /**
         * 防闪屏
         */
        getContext().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        isFull = true;
        mLift = moduleContext.optInt("lift", 0);
        mTop = moduleContext.optInt("top", 0);
        mHight = moduleContext.optInt("hight", 100);
        mWidth = moduleContext.optInt("width", -1);

        mId = moduleContext.optInt("mId", -1);
        mFixed = moduleContext.optBoolean("fixed", false);
        mIndexName = moduleContext.optString("indexName", "");
        mFllScreen = moduleContext.optBoolean("fullScreen", false);
        mUri = moduleContext.optString("uri", "http://resource.apicloud.com/video/apicloud3.mp4");
        mMaxProbeTime = moduleContext.optInt("maxprobetime", 2000);
        mImageUri = moduleContext.optString("imageuri", "");

        mListImageWidth = moduleContext.optInt("listImagewidth", 300);
        mListImageHeight = moduleContext.optInt("listImageheight", 500);


        mTitleText = moduleContext.optString("titleText", "标题获取失败");
        mHandImageUri = moduleContext.optString("handImageUri", "");


        mFllFixed = moduleContext.optBoolean("fixedFull", true);
        mIndexFullName = moduleContext.optString("indexFullName", "");


        if (mRela == null) {
            //初始化视频播放器
            mVV = new BDCloudVideoView(getContext());
            mMediaController = new SimpleMediaController(getContext());
            mRela = new RelativeLayout(getContext());
            mRela.setBackgroundColor(Color.BLACK);
        } else {
            removeViewFromCurWindow(mRela);
            mRela.setBackgroundColor(Color.BLACK);
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
        params.setMargins(mLift, mTop, 0, 0);
        //main
        insertViewToCurWindow(mRela, params, mIndexFullName, mFllFixed);
        initViodView();


    }

    //点击暂停
    public void jsmethod_openPause(UZModuleContext moduleContext) {
        mVV.pause();
    }

    //点击开始图片
    public void jsmethod_openSatrt(UZModuleContext moduleContext) {

        if (!mVV.isPlaying()) {
            if (mIsStoped) {
                initViodView();
                mIsStoped = false;
            } else {
                mVV.start();
            }
        }
    }

    //点击停止
    public void jsmethod_openStop(UZModuleContext moduleContext) {
        mIsStoped = true;
        if (mVV.isPlaying()) {
            mVV.stopPlayback();
        }
    }

    //点击播放切换播放目录
    public void jsmethod_openNextPlay(UZModuleContext moduleContext) {
        mUri = moduleContext.optString("uri", "rtmp://live.hkstv.hk.lxdns.com/live/hks");
        boolean isPaly = moduleContext.optBoolean("isPlay", true);
        mVV.setVideoPath(mUri);
        mMediaController.getSeekBar().setProgress(0);
        if (isPaly) {
            mVV.start();

        }
    }

    //设置音量
    public void jsmethod_openVolumeSetting(UZModuleContext moduleContext) {

        double mVolume = moduleContext.optDouble("volume", 1.0);
        float nVolume = (float) mVolume;
        //设置声音
        mVV.setVolume(nVolume, nVolume);
        mMediaController.getMusicClose().setSelected(false);
    }

    //设置是否循环
    public void jsmethod_openLooper(UZModuleContext moduleContext) {

        boolean mLooper = moduleContext.optBoolean("looper", false);
        mVV.setLooping(mLooper);
        mVV.start();
    }

    //跳转到指定位置
    public void jsmethod_openSkipPostion(UZModuleContext moduleContext) {

        int mPosition = moduleContext.optInt("position", 1000);
        double mSpeed = moduleContext.optDouble("speed", 1.0);
        int mMaxSize = moduleContext.optInt("maxsizeinbytes", 1024);
        int mMaxProbeSize = moduleContext.optInt("maxprobesize", 1024);

        float speed = (float) mSpeed;
        mVV.seekTo(mPosition);
        mVV.setSpeed(speed);
        mVV.setMaxCacheSizeInBytes(mMaxSize);
        mVV.setMaxProbeSize(mMaxProbeSize);
        mVV.start();

    }

    //移除视频播放器
    public void jsmethod_removeVido(UZModuleContext moduleContext) {
        if (mRela != null) {
            mVV.stopPlayback();// 释放播放器资源
            mVV.release();// 释放播放器资源和显示资源
            removeViewFromCurWindow(mRela);
            mHandler.removeCallbacksAndMessages(null);
        }

    }

    //是否显示进度条
    public void jsmethod_showProgress(UZModuleContext moduleContext) {
        boolean isShown = moduleContext.optBoolean("isShown", false);
        //进度条以及进度条的时间
        if (!isShown) {
            mMediaController.getSeekBar().setVisibility(View.INVISIBLE);
            mMediaController.getReadTime().setVisibility(View.INVISIBLE);
            mMediaController.getAllTime().setVisibility(View.INVISIBLE);
        } else {
            mMediaController.getSeekBar().setVisibility(View.VISIBLE);
            mMediaController.getReadTime().setVisibility(View.VISIBLE);
            mMediaController.getAllTime().setVisibility(View.VISIBLE);
        }
    }

    //第一次执行
    public void jsmethod_firstToPlay(UZModuleContext moduleContext) {

        //开始播放，当点击视频前的图片时才能播放
        fullImage = true;
        //设置透明背景，并且播放
        Glide.with(getContext())
                .load("")
                .error(R.drawable.writback)
                .into(mMediaController.getViodPicrure());
        mVV.start();
        if (!mVV.isPlaying() && fullImage) {
            mVV.start();
        }

    }

    //仅仅是提供横竖屏切换(横屏)
    public void jsmethod_transverseScream(UZModuleContext moduleContext) {
        getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        isFull = true;
    }

    //仅仅是提供横竖屏切换(竖屏)
    public void jsmethod_verticalScream(UZModuleContext moduleContext) {
        getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        isFull = false;
    }

    private void initViodView() {
        mMediaController.getShopImage().setVisibility(View.VISIBLE);
        //设置图片的大小
        //        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mMoveImageWidth, mMoveImageHeigh);
        //        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        //        params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        //        mMediaController.getSliedBar().setLayoutParams(params);


        //设置侧滑点击事件
        //侧面划入滑出效果
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("TranslationX", 0f, -mListImageWidth);
        PropertyValuesHolder animatorw = PropertyValuesHolder.ofFloat("TranslationX", -mListImageWidth, 0.0f);
        mAnimtion = ObjectAnimator.ofPropertyValuesHolder(mMediaController.getSliedBar(), animator, animatorw).setDuration(0);
        mAnimtion.start();


        //侧滑点击事件
        mMediaController.getSliedBar().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCloseOpen) {
                    mAnimtion.start();
                    mMediaController.setListVisible(false, itemBeens, mListImageWidth, mListImageHeight);
                    mMediaController.getShopImage().setVisibility(View.VISIBLE);
                } else {
                    mAnimtion.reverse();
                    mMediaController.getShopImage().setVisibility(View.GONE);
                    mMediaController.setListVisible(true, itemBeens, mListImageWidth, mListImageHeight);
                }
                mCloseOpen = !mCloseOpen;
            }
        });


        //TODO：这里判断是横竖屏，ture为全屏播放
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(false);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(true);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);

            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);

            if (mAnimtion != null) {
                mAnimtion.start();
                mCloseOpen = false;
            }
        }
        //视频比例和屏幕比例不一致的话，默认不能全屏问题
        if (mFllScreen) {
            //视频占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
        } else {
            //            视频不占满整个屏幕
            mVV.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        }
        //保证不息屏
        getContext().getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //设置播放器与播放器播放器所搭载的布局一致
        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(-1, -1);
        //        rllp.addRule(RelativeLayout.CENTER_IN_PARENT);
        mRela.removeAllViews();
        mRela.addView(mVV, rllp);
        mRela.addView(mMediaController);
        mVV.setVideoPath(mUri);
        mVV.setMaxProbeTime(mMaxProbeTime); // 设置首次缓冲的最大时长
        mVV.setTimeoutInUs(1000000);

        //播放器准备好的监听
        //        mVV.setOnPreparedListener(this);
        //        mVV.setOnCompletionListener(this);

        //播放错误监听
        mVV.setOnErrorListener(this);
        //播放信息监听
        mVV.setOnInfoListener(this);

        //该方法主要用于进度条的监听
        mVV.setOnBufferingUpdateListener(this);
        //播放状态监听，主要用于进度条的监听
        mVV.setOnPlayerStateListener(this);

        //开始播放，当点击视频前的图片时才能播放
        if (!mVV.isPlaying() && fullImage) {
            mVV.start();
        }

        //加载图片
        if (!fullImage) {
            Glide.with(getContext())
                    .load(mImageUri)
                    .placeholder(R.drawable.loading)
                    .error(R.drawable.loading)
                    .error(R.drawable.ic_play)
                    .into(mMediaController.getViodPicrure());
        }
        //TODO:点击开始和暂停按钮
        mMediaController.getImageStart().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mVV.isPlaying()) {
                    mVV.pause();
                } else {
                    mVV.start();
                }
                if (!fullImage) {
                    //设置透明背景，并且播放
                    Glide.with(getContext())
                            .load("")
                            .error(R.drawable.writback)
                            .into(mMediaController.getViodPicrure());
                    mVV.start();
                }
                fullImage = true;
            }
        });


        //TODO:设置进度条的点击事件
        mMediaController.getSeekBar().setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.getReadTime().setText(formatMilliSecond(progress));
                    }
                });
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (mVV.getDuration() > 0) {
                    int i = (mVV.getDuration() * progress) / 10000;
                    mVV.seekTo(i);
                    seekBar.setEnabled(true);
                } else {
                    seekBar.setEnabled(false);
                }
            }
        });
        //TODO:点击进行横竖屏切换
        mMediaController.getFullSecream().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMediaController.getShopImage().setVisibility(View.VISIBLE);
                if (isFull) {
                    //TODO:先移除布局ture为全屏播放
                    removeViewFromCurWindow(mRela);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(mWidth, mHight);
                    params.setMargins(mLift, mTop, 0, 0);

                    //再添加布局
                    insertViewToCurWindow(mRela, params, mIndexName, mFixed);
                    mMediaController.getFullSecream().setSelected(false);
                    isFull = !isFull;
                    //再开始播放
                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    initPlay();

                    JSONObject object = new JSONObject();
                    try {
                        object.put("mIsFull", 2);
                        object.put("mId", mId);
                        //设置为false为不间断的想后台发送数据
                        mModuleContext.success(object, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    //先移除布局
                    removeViewFromCurWindow(mRela);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
                    params.setMargins(0, 0, 0, 0);

                    //再添加布局
                    insertViewToCurWindow(mRela, params, mIndexFullName, mFllFixed);

                    mMediaController.getFullSecream().setSelected(true);
                    isFull = !isFull;
                    //再开始播放
                    //这里仅仅是横竖屏不涉及播放，并且解决返回键没有点击事件的
                    initPlay();

                    JSONObject object = new JSONObject();
                    try {
                        object.put("mIsFull", 1);
                        object.put("mId", mId);
                        //设置为false为不间断的想后台发送数据
                        mModuleContext.success(object, false);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        //点击静音
        mMediaController.getMusicClose().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMusic = !isMusic;
                if (isMusic) {
                    mMediaController.getMusicClose().setSelected(true);
                    mVV.setVolume(0, 0);
                } else {
                    mMediaController.getMusicClose().setSelected(false);
                    mVV.setVolume(1, 1);
                }

            }
        });


        //设置ListVIew的条目点击事件
        mMediaController.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAnimtion.start();
                mCloseOpen = false;
                mMediaController.getListView().setVisibility(View.INVISIBLE);
                mVV.setVideoPath(itemBeens.get(position).getVidoUri());
                mId = Integer.parseInt(itemBeens.get(position).getId());
                mMediaController.getTitleText().setText(itemBeens.get(position).getHandText());
                Glide.with(getContext())
                        .load(mHandImageUri)
                        .placeholder(R.drawable.lively)
                        .error(R.drawable.lively)
                        .into(mMediaController.getTitleImage());
                mMediaController.getShopImage().setVisibility(View.VISIBLE);
                if (!fullImage) {
                    Glide.with(getContext())
                            .load("")
                            .error(R.drawable.writback)
                            .into(mMediaController.getViodPicrure());
                }
                fullImage = true;
                mVV.start();
            }
        });

        //点击分享
        mMediaController.getShareScream().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                JSONObject object = new JSONObject();
                try {
                    object.put("share", 100);
                    object.put("mId", mId);
                    //设置为false为不间断的想后台发送数据
                    mModuleContext.success(object, false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

        //点击购物车
        mMediaController.getShopImage().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                JSONObject object = new JSONObject();
                try {
                    object.put("shoping", 200);
                    object.put("mId", mId);
                    //设置为false为不间断的想后台发送数据
                    mModuleContext.success(object, false);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

        mMediaController.getTitleText().setText(mTitleText);
        Glide.with(getContext())
                .load(mHandImageUri)
                .placeholder(R.drawable.lively)
                .error(R.drawable.lively)
                .into(mMediaController.getTitleImage());

    }

    private void initPlay() {
        if (isFull) {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(false);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.VISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
        } else {
            getContext().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //切换全屏播放的按钮
            mMediaController.getFullSecream().setSelected(true);
            //侧滑菜单是否显示
            mMediaController.getSliedBar().setVisibility(View.INVISIBLE);
            //侧滑菜单是否显示
            mMediaController.getListView().setVisibility(View.INVISIBLE);
            if (mAnimtion != null) {
                mAnimtion.start();
                mCloseOpen = false;
            }
        }
    }

    @Override
    public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
        return false;
    }

    @Override
    public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int percent) {
        if (mMediaController != null && mVV != null) {
            final long currentPosition = mVV.getCurrentPosition();
            long duration = mVV.getDuration();
            //TODO:设置更细化的进度
            if (currentPosition > 0 && duration > 0) {
                long pos = 10000L * currentPosition / duration;
                mMediaController.seatProgress((int) pos);
                mMediaController.getSeekBar().setEnabled(true);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMediaController.getReadTime().setText(formatMilliSecond(mVV.getCurrentPosition()));
                        mMediaController.getAllTime().setText(formatMilliSecond(mVV.getDuration()));
                    }
                });
            } else {
                mMediaController.getSeekBar().setEnabled(false);
            }
        }
        JSONObject object = new JSONObject();
        try {
            object.put("currentposition", iMediaPlayer.getCurrentPosition());
            object.put("duration", iMediaPlayer.getDuration());
            object.put("mId", mId);
            if (isFull) {
                object.put("mIsFull", 1);
            } else {
                object.put("mIsFull", 2);
            }
            //设置为false为不间断的想后台发送数据
            mModuleContext.success(object, false);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPlayerStateChanged(PlayerState nowState) {
        System.out.println("播放状态监听");
        PlayerState state = mVV.getCurrentPlayerState();
        if (state == PlayerState.STATE_IDLE || state == PlayerState.STATE_ERROR) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int currentPosition = mVV.getCurrentPosition();
                    int duration = mVV.getDuration();
                    mMediaController.getReadTime().setText(formatMilliSecond(currentPosition));
                    mMediaController.getAllTime().setText(formatMilliSecond(duration));
                }
            });
            //播放监听
        } else if (state == PlayerState.STATE_PLAYING) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);
        } else if (state == PlayerState.STATE_PAUSED || state == PlayerState.STATE_IDLE) {
            mHandler.sendEmptyMessage(1);
        } else if (state == PlayerState.STATE_PREPARED) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.sendEmptyMessage(2);
                    mHandler.postDelayed(this, 1000);
                }
            }, 1000);

        }
    }


    private String formatMilliSecond(int milliSecond) {
        int seconds = milliSecond / 1000;
        int hh = seconds / 3600;
        int mm = seconds % 3600 / 60;
        int ss = seconds % 60;
        String strTemp = null;
        if (0 != hh) {
            strTemp = String.format("%02d:%02d:%02d", hh, mm, ss);
        } else {
            strTemp = String.format("%02d:%02d", mm, ss);
        }
        return strTemp;
    }

    public void jsmethod_showPeopleNumber(UZModuleContext moduleContext) {

        mPeoploNumber = moduleContext.optString("peopleNumber", "999人在线");
        mMediaController.getPeoploNumber().setText(mPeoploNumber);

    }


    private List<String> mPermissionList;//权限集合
    private static final int MY_PERMISIONLIST                  = 0x22;//申请权限的返回码
    private static final int REQUEST_TAKE_GALLERY_VIDEO        = 0x23;
    private static final int REQUEST_TAKE_GALLERY_VIDEO_KITKAT = 0x24;

    private boolean mLightOpen = false;
    private boolean isStart    = false;
    private boolean isBigin    = false;
    private VideoLivePlay      mLivePlay;//录制直播初始化
    private int                mCurrentCamera;
    private LiveStreamSession  mSession;
    private String             mUpUri;//上传视频的地址
    private String             mNativeIndexName;
    private String             mUpImageUri;//上传图片uri
    private NativeVideo        mNativeVideo;
    private LiveCaptureSession mLiveCaptureSession;

    private ImageButton mCancel;
    private ImageButton mSure;
    private ImageView   mBiginNativeVideo;
    private AtomicLong tick = new AtomicLong(0);
    private String       mp4SavedPath;//录制文件的路径
    private String       mNewMp4SavedPath;//新生成的路径
    private OkHttpClient mOkHttpClient;//初始化网络请求类

    private Disposable captureTask;
    private CompletedView mUpCompletedView;
    private Dialog mProgressDialog;
    //TODO:打开直播
    public void jsmethod_openLiveTelecast(UZModuleContext moduleContext) {

        //设置摄像头的一种状态
        mLightOpen = false;
        //是否启动了播放
        isStart = false;
        //是否开始播放了
        isBigin = false;
        String mIndexName = moduleContext.optString("indexName", "");
        boolean mFixed = moduleContext.optBoolean("fixed", false);
        String mUri = moduleContext.optString("uri", "");
        int mVideoWidth = moduleContext.optInt("videowidth", 720);
        int mVideoHeight = moduleContext.optInt("videoheight", 1280);
        int mVideoFPS = moduleContext.optInt("videofps", 25);
        int mCameraOrientation = moduleContext.optInt("cameraorientation", 90);
        int mOutOrientation = moduleContext.optInt("outorientation", 0);

        //TODO:保证不息屏
        Window win = getContext().getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
        params.setMargins(0, 0, 0, 0);
        if (mLivePlay == null) {
            mLivePlay = new VideoLivePlay(getContext());
        } else {
            removeViewFromCurWindow(mLivePlay);
        }


        //加载view
        insertViewToCurWindow(mLivePlay, params, mIndexName, mFixed);
        BDRtmpSessionBasic.UserRole mRole = BDRtmpSessionBasic.UserRole.Host;
        // 1-->主播  2-->高级观众 3-->普通观众
        mRole = getUserRoleByType(1);

        //获取当前摄像头状态（初始化默认为前置摄像头）
        mCurrentCamera = LiveConfig.CAMERA_FACING_FRONT;
        // 配置录制参数
        LiveConfig.Builder builder = new LiveConfig.Builder();
        builder.setVideoWidth(mVideoWidth)// 设置输出视频的宽（像素个数）
                .setVideoHeight(mVideoHeight) // 设置输出视频的高（像素个数）
                .setCameraOrientation(mCameraOrientation) // 设置相机旋转参数，通常横屏传0度，竖屏传90度
                .setVideoFPS(mVideoFPS) // 设置帧率
                .setInitVideoBitrate(400000)// 设置视频编码初始码率
                .setMinVideoBitrate(100000) // 设置视频编码最低码率（用于动态码率控制）
                .setMaxVideoBitrate(800000)// 设置视频编码最高码率（用于动态码率控制）
                .setVideoEnabled(true)
                .setAudioSampleRate(44100)
                .setAudioBitrate(64000)
                .setOutputOrientation(mOutOrientation)
                .setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT); // 设置所使用的相机,默认前置摄像头

        // 初始化录制Session
        mSession = new LiveStreamSession(getContext(), builder.build());
        // 绑定SurfaceHolder
        mSession.setSurfaceHolder(mLivePlay.getSurfaceView().getHolder());
        //设置回调监听
        //        mSession.setRtmpEventListener(this);
        //设置地址等
        mSession.configRtmpSession(mUri, mRole);
        //设置连麦的回调监听
        //        mSession.setRtmpEventListener(this);

        // 美颜滤镜
        //        beautyFilter = new GPUImageSoftenBeautyFilter();
        //        // 颜色调整滤镜
        //        colorAdjustFilter = new ColorAdjustFilter(NaxiangVido.this);
        //        // 其他滤镜：如风格滤镜，自定义滤镜
        //        customFilter = new GPUImageFilter();
        //
        //        List<GPUImageFilter> filters = new ArrayList<>();
        //
        //        filters.add(beautyFilter);
        //        filters.add(colorAdjustFilter);
        //        filters.add(customFilter);
        //        // 设置美颜、色彩调整、风格等滤镜链
        //        mSession.setGPUImageFilters(filters);

        //        // 设置背景乐
        //        mSession.configBackgroundMusic(boolean enableBGM, String bgmPath, boolean isLooping)
        //        // 设置背景乐区间，单位为微妙（us）
        //        mSession.configBackgroundMusicClip(long clipStartInUSec, long clipDurationInUSec)

        //        // 设置录音音量增益，取值[0f, 1f]
        //        mSession.setRecordTrackGain(float gain);
        //        // 设置背景音音量增益，取值[0f, 1f]
        //        mSession.setBGMTrackGain(float gain);


        //        // 开启或关闭闪光灯
        //        mSession.toggleFlash(boolean flag);
        //        // 是否可以切换摄像头
        //        mSession.canSwitchCamera();
        //        // 切换摄像头
        //        mSession.switchCamera(int cameraId);
        //        // focus到具体位置
        //        mSession.focusToPoint(int x, int y);
        //        // 获取最大缩放因子
        //        mSession.getMaxZoomFactor();
        //        // 设置缩放因子
        //        mSession.setZoomFactor(int factor);

        // 发起会话请求
        // 参数userStreamUrl为被叫的rtmp推流地址
        // 参数userId为被叫的业务ID
        //        mSession.startCallWith(userStreamUrl, userId);


        // 结束（或取消）会话
        // 参数userStreamUrl为呼叫者（小主播）的rtmp推流地址
        // 参数userId为呼叫者（小主播）的业务ID
        //        mSession.stopCallWith(userStreamUrl, userId);
        mSession.setupDevice();


        //检查摄像头是否可用
        if (!mSession.canSwitchCamera()) {
            JSONObject object = new JSONObject();
            try {
                object.put("cameraBroken", "120");
                //设置为false为不间断的想后台发送数据
                mModuleContext.success(object, true);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        //闪光灯
        final ImageView mLightImage = mLivePlay.getOpenLight();
        //前后摄像头改变
        ImageView mChengeVideo = mLivePlay.getChengeVideo();
        //开始暂停直播
        final ImageView mBiginVideo = mLivePlay.getBiginVideo();

        //开启闪光灯
        mLightImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentCamera == LiveConfig.CAMERA_FACING_FRONT) {
                    Toast.makeText(getContext(), "使用前置摄像头时不能开启闪光灯", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (mLightOpen) {
                        mSession.toggleFlash(false);
                    } else {
                        mSession.toggleFlash(true);
                    }
                    mLightOpen = !mLightOpen;
                    if (mLightImage.isSelected()) {
                        mLightImage.setSelected(false);
                    } else {
                        mLightImage.setSelected(true);
                    }
                }
            }
        });


        //切换摄像头
        mChengeVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //摄像头是否可用
                if (mSession.canSwitchCamera()) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurrentCamera == LiveConfig.CAMERA_FACING_BACK) {
                                mCurrentCamera = LiveConfig.CAMERA_FACING_FRONT;
                                mSession.switchCamera(mCurrentCamera);
                                if (mLightOpen) {
                                    mSession.toggleFlash(false);
                                    mLightOpen = !mLightOpen;
                                    mLightImage.setSelected(false);
                                }
                            } else {
                                mCurrentCamera = LiveConfig.CAMERA_FACING_BACK;
                                mSession.switchCamera(mCurrentCamera);

                            }
                        }
                    }).start();
                } else {
                    Toast.makeText(getContext(), "抱歉！该分辨率下不支持切换摄像头！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //点击开始按钮
        mBiginVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int state = NetUtils.getNetWorkState(getContext());
                if (state == -1) {
                    Toast.makeText(getContext(), "当前没有网络,请检查网络", Toast.LENGTH_SHORT).show();
                    return;
                } else if (state == 0) {
                    Toast.makeText(getContext(), "当前使用的是移动流量", Toast.LENGTH_SHORT).show();
                }

                if (isStart) {
                    if (isBigin) {
                        // 恢复推流
                        mSession.resumeStreaming();
                        mBiginVideo.setSelected(true);

                    } else {
                        // 暂停推流
                        mSession.pauseStreaming();
                        mBiginVideo.setSelected(false);
                    }
                    isBigin = !isBigin;
                } else {
                    // 开始推流
                    mSession.startStreaming();
                    mBiginVideo.setSelected(true);
                    isStart = true;
                }
            }
        });

        ToastMake.showToast(getContext(), "打开直播");
    }

    //TODO:移除直播
    public void jsmethod_removeLiveTelecast(UZModuleContext moduleContext) {

        if (mSession != null) {
            // 停止推流
            mSession.stopStreaming();
            // 销毁，不再使用时调用
            mSession.destroyRtmpSession();
            mSession.releaseDevice();
        }
        if (mLivePlay != null) {
            removeViewFromCurWindow(mLivePlay);
            mLivePlay = null;
        }
    }

    //TODO:开启本地录制
    public void jsmethod_openNativeVideo(UZModuleContext moduleContext) {
        //TODO:保证不息屏
        Window win = getContext().getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mNativeIndexName = moduleContext.optString("indexName", "");
        boolean mFixed = moduleContext.optBoolean("fixed", false);
        mUpUri = moduleContext.optString("uri", "");
        mUpImageUri = moduleContext.optString("imageUri", "");
        int mVideoWidth = moduleContext.optInt("videowidth", 720);
        int mVideoHeight = moduleContext.optInt("videoheight", 1280);
        int mVideoFPS = moduleContext.optInt("videofps", 25);
        int mCameraOrientation = moduleContext.optInt("cameraorientation", 90);
        int mOutOrientation = moduleContext.optInt("outorientation", 0);


        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(-1, -1);
        params.setMargins(0, 0, 0, 0);

        if (mNativeVideo == null) {
            mNativeVideo = new NativeVideo(getContext());
        } else {
            removeViewFromCurWindow(mNativeVideo);
        }

        //初始化摄像头的位置
        mCurrentCamera = LiveConfig.CAMERA_FACING_BACK;
        //设置到界面上
        insertViewToCurWindow(mNativeVideo, params, mNativeIndexName, mFixed);
        // 配置录制参数
        LiveConfig.Builder builder = new LiveConfig.Builder();
        builder.setCameraOrientation(mCameraOrientation) // 设置相机旋转参数，通常横屏传0度，竖屏传90度
                .setVideoFPS(mVideoFPS)// 设置帧率
                .setOutputOrientation(mOutOrientation) // 设置产出的视频的逆时针旋转方向，该参数最终用于VideoFilter的setEncodeSize接口
                .setCameraId(LiveConfig.CAMERA_FACING_BACK)  // 设置所使用的相机
                .setVideoWidth(mVideoWidth)// 设置输出视频的宽（像素个数）
                .setVideoHeight(mVideoHeight); // 设置输出视频的高（像素个数）


        SurfaceView nativeSurface = mNativeVideo.getNativeSurface();
        // 初始化录制Session
        mLiveCaptureSession = new LiveCaptureSession(getContext(), builder.build());
        mLiveCaptureSession.setSurfaceHolder(nativeSurface.getHolder());

        mLiveCaptureSession.setCaptureErrorListener(new LiveCaptureSession.CaptureErrorListener() {
            @Override
            public void onError(int error, String desc) {
                //                Toast.makeText(getContext(), "录像设备打开失败", Toast.LENGTH_SHORT).show();
                return;
            }
        });


        //        // 美颜滤镜
        //        GPUImageSoftenBeautyFilter beautyFilter = new GPUImageSoftenBeautyFilter();
        //        // 颜色调整滤镜
        //        ColorAdjustFilter colorAdjustFilter = new ColorAdjustFilter(getContext());
        //        // 其他滤镜：如风格滤镜，自定义滤镜
        //        GPUImageFilter customFilter = new GPUImageFilter();
        //        List<GPUImageFilter> filterList = new ArrayList<>();
        //        filterList.add(beautyFilter);
        //        filterList.add(colorAdjustFilter);
        //        filterList.add(customFilter);
        //        // 设置美颜、色彩调整、风格等滤镜链
        //        mLiveCaptureSession.setGPUImageFilters(filterList);

        // 初始化录音与捕获视频的device. 在创建Session时仅调用一次；
        mLiveCaptureSession.setupDevice();

        //重新启动编码器
        mLiveCaptureSession.resume();

        //开启闪光灯
        final ImageView openNativeLight = mNativeVideo.getOpenNativeLight();
        //初始化默认闪光灯是关闭的
        Camera cam = Camera.open();
        Camera.Parameters p = cam.getParameters();
        String flashMode = p.getFlashMode();//获取闪光灯的状态

        if (TextUtils.equals(p.FLASH_MODE_ON, flashMode)) {
            mLightOpen = true;
            openNativeLight.setSelected(true);
        } else {
            mLightOpen = false;
            openNativeLight.setSelected(false);
        }


        openNativeLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentCamera == LiveConfig.CAMERA_FACING_FRONT) {
                    Toast.makeText(getContext(), "使用前置摄像头时不能开启闪光灯", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (mLightOpen) {
                        mLiveCaptureSession.toggleFlash(false);
                    } else {
                        mLiveCaptureSession.toggleFlash(true);
                    }
                    mLightOpen = !mLightOpen;
                    if (openNativeLight.isSelected()) {
                        openNativeLight.setSelected(false);
                    } else {
                        openNativeLight.setSelected(true);
                    }
                }
            }
        });

        //切换摄像头
        ImageView chengNativeVideo = mNativeVideo.getChengNativeVideo();
        chengNativeVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //摄像头是否可用
                if (mLiveCaptureSession.canSwitchCamera()) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurrentCamera == LiveConfig.CAMERA_FACING_BACK) {
                                mCurrentCamera = LiveConfig.CAMERA_FACING_FRONT;
                                mLiveCaptureSession.switchCamera(mCurrentCamera);
                                if (mLightOpen) {
                                    mLiveCaptureSession.toggleFlash(false);
                                    mLightOpen = !mLightOpen;
                                }
                            } else {
                                mCurrentCamera = LiveConfig.CAMERA_FACING_BACK;
                                mLiveCaptureSession.switchCamera(mCurrentCamera);
                            }
                        }
                    }).start();
                } else {
                    Toast.makeText(getContext(), "抱歉！该分辨率下不支持切换摄像头！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //录制开始点击删除
        mCancel = mNativeVideo.getCancel();
        //录制完成点击确定
        mSure = mNativeVideo.getSure();
        //开始播放按钮
        mBiginNativeVideo = mNativeVideo.getBiginNativeVideo();

        //点击开始录制
        mBiginNativeVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCancel.setVisibility(View.VISIBLE);
                mSure.setVisibility(View.VISIBLE);
                if (!tryPauseCapture()) {
                    // 如果还没开始录制
                    if (tick.get() == 0) {
                        System.out.println("还没开始录制");
                        mp4SavedPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
                                .getPath() + "/NaXiang-" + System.currentTimeMillis() + ".mp4";
                        // 初始化mp4格式封装器
                        mLiveCaptureSession.configMp4Muxer(mp4SavedPath);
                        mLiveCaptureSession.start();
                        mBiginNativeVideo.setSelected(true);

                    } else {
                        System.out.println("已经开始录制了");
                        mLiveCaptureSession.resume();
                        mBiginNativeVideo.setSelected(true);

                    }

                    captureTask = Flowable.interval(10, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .map(new Function<Long, Long>() {
                                @Override
                                public Long apply(@NonNull Long aLong) throws Exception {
                                    return tick.getAndIncrement();
                                }
                            })
                            .takeWhile(new Predicate<Long>() {
                                @Override
                                public boolean test(@NonNull Long aLong) throws Exception {

                                    return true;
                                }
                            })
                            .doOnComplete(new Action() {
                                @Override
                                public void run() throws Exception {
                                    tryPauseCapture();
                                    mBiginNativeVideo.setSelected(false);
                                }
                            })
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(@NonNull Long aLong) throws Exception {
                                }
                            });
                }
            }
        });

        //取消删除视频
        mCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delateRido();
            }
        });

        //确定视频
        mSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickFinish();
            }
        });


    }

    //TODO:移除录制视频
    public void jsmethod_removeNativeVideo(UZModuleContext moduleContext) {

        if (mLiveCaptureSession != null) {
            mLiveCaptureSession.stop();
            mLiveCaptureSession.release();
            mLiveCaptureSession = null;
        }
    }

    //TODO:选择本地文件上传
    public void jsmethod_chioceVideo(UZModuleContext moduleContext) {

        mUpUri = moduleContext.optString("uri", "");
        mUpImageUri = moduleContext.optString("uri", "");
        mNativeIndexName = moduleContext.optString("indexName", "index_frm");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "选择视频文件"), REQUEST_TAKE_GALLERY_VIDEO);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("video/*");
            startActivityForResult(intent, REQUEST_TAKE_GALLERY_VIDEO_KITKAT);
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && null != data) {
            Uri originalUri = null;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                originalUri = data.getData();
            } else if (requestCode == REQUEST_TAKE_GALLERY_VIDEO_KITKAT) {
                originalUri = data.getData();
                final int takeFlags = data.getFlags()
                        & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Check for the freshest data.
                getContext().getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
            }
            final String videoPath = FileUtils.getPath(getContext(), originalUri);


            //向网上上传文件,在子线程中进行
            new Thread(new Runnable() {
                @Override
                public void run() {
                    upNetFile(videoPath);
                }
            }).start();

        } else {
            Toast.makeText(getContext(), "读取文件路径失败", Toast.LENGTH_SHORT).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //TODO:android 6.0必须的权限
    public void jsmethod_shudlePermission(UZModuleContext moduleContext) {
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
        if (mPermissionList == null) {
            mPermissionList = new ArrayList<>();
        } else {
            mPermissionList.clear();
        }


        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(getContext(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                //将List转为数组
                String[] permissionarrs = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(getContext(), permissionarrs, MY_PERMISIONLIST);
            }
        }


    }

    //TODO:android 核对是否有6.0权限
    public void jsmethod_checkPermision(UZModuleContext moduleContext) {
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
        if (mPermissionList == null) {
            mPermissionList = new ArrayList<>();
        } else {
            mPermissionList.clear();
        }
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(getContext(), permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }
            if (!mPermissionList.isEmpty()) {
                Intent intent = new Intent(
                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getContext().getPackageName()));
                startActivity(intent);

                JSONObject object = new JSONObject();
                try {
                    object.put("haveNoPermission", "105");
                    //设置为false为不间断的想后台发送数据
                    mModuleContext.success(object, true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return;
            }
        }

    }


    private BDRtmpSessionBasic.UserRole getUserRoleByType(int type) {
        switch (type) {
            case 1:
                return BDRtmpSessionBasic.UserRole.Host;
            case 2:
                return BDRtmpSessionBasic.UserRole.Guest;
            default:
                return BDRtmpSessionBasic.UserRole.Audience;
        }
    }

    /**
     * @return 是否在调用该方法时已经开始拍摄
     */
    private synchronized boolean tryStopCapture() {
        // 如果没有开始拍摄直接返回
        if (tick.get() == 0) {
            return false;
        }
        if (captureTask != null && !captureTask.isDisposed()) {
            captureTask.dispose();
            captureTask = null;
        }
        mBiginNativeVideo.setSelected(false);
        mLiveCaptureSession.destroyMp4Muxer();
        mLiveCaptureSession.stop();
        return true;
    }

    /**
     * @return 如果由录制状态进入暂停状态则返回 true
     */
    private synchronized boolean tryPauseCapture() {
        if (tick.get() > 0 && captureTask != null && !captureTask.isDisposed()) {
            mLiveCaptureSession.pause();
            mBiginNativeVideo.setSelected(false);
            System.out.println("暂停了");
            captureTask.dispose();
            captureTask = null;
            return true;
        }
        return false;
    }

    public void delateRido() {
        tryStopCapture();
        File file = new File(mp4SavedPath);
        if (file.exists()) {
            file.delete();
        }

    }

    public void onClickFinish() {
        tryStopCapture();
        //对视频添加效果等
        //获取全局未捕获的异常
        //        CrashHandler crashHandler = CrashHandler.getInstance();
        //        crashHandler.init(getContext());

        mNativeVideo.getCompletedView().setVisibility(View.VISIBLE);
        mNativeVideo.getCompletedView().setProgress(0);
        //在子线程中进行
        new Thread(new Runnable() {
            @Override
            public void run() {
                ProcessConfig.Builder builder = new ProcessConfig.Builder();
                MediaProcessSession mMediaProcessSession = new MediaProcessSession(getContext(), builder.build());
                FileUtils.configProcessConfig(mp4SavedPath, builder);
                mMediaProcessSession.setPlaybackRate(90);
                mMediaProcessSession.setMediaFilePath(mp4SavedPath);
                mNewMp4SavedPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath()
                        + "/NaXiang-" + System.currentTimeMillis() + ".mp4";
                System.out.println("mp4SavedPath==新生成的" + mNewMp4SavedPath);
                //设置源视频文件路径2
                mMediaProcessSession.configMp4Saver(true, mNewMp4SavedPath);//设置合成视频的存储路径
                mMediaProcessSession.setProcessStateListener(new ProcessStateListener() {
                    @Override
                    public void onProgress(final int progress) {
                        mNativeVideo.getCompletedView().setProgress(progress);
                    }

                    @Override
                    public void onFinish(boolean isSuccess, int what) {

                        if (isSuccess) {
                            System.out.println("合成成功");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mNativeVideo.getCompletedView().setVisibility(View.INVISIBLE);
                                    initDialog();
                                }
                            });
                        } else {
                            System.out.println("合成失败，错误码：" + what);
                            new File(mp4SavedPath).delete();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mNativeVideo.getCompletedView().setVisibility(View.INVISIBLE);
                                }
                            });
                        }
                    }
                });
                mMediaProcessSession.start();

            }
        }).start();
    }

    //初始化Dialog样式
    private void initDialog() {
        //1.创建一个Dialog对象，如果是AlertDialog对象的话，弹出的自定义布局四周会有一些阴影，效果不好
        final Dialog mDialog = new Dialog(getContext());
        //去除标题栏
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View dialogView = inflater.inflate(R.layout.mo_uploadxinvideo_dialog_layout, null);

        //上传到网上
        dialogView.findViewById(R.id.uplaodefile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        upNetFile(mNewMp4SavedPath);
                    }
                }).start();
            }
        });
        //保存到本地
        dialogView.findViewById(R.id.nativefile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                ToastMake.showToast(getContext(), "视频保存的位置为" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath());
            }
        });
        //将自定义布局设置进去
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);
        //设置点击其它地方不让消失弹窗
        mDialog.setCancelable(true);
    }

    //TODO:上传文件
    private void upNetFile(String path) {
        int state = NetUtils.getNetWorkState(getContext());
        if (state == -1) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "当前没有网络,请检查网络", Toast.LENGTH_SHORT).show();
                }
            });
            return;
        } else if (state == 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "当前使用的是移动流量", Toast.LENGTH_SHORT).show();
                }
            });

        }
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient.Builder()
                    //                .addInterceptor(new LoggerInterceptor("TAG"))
                    .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                    .readTimeout(10000L, TimeUnit.MILLISECONDS)
                    //其他配置
                    .build();
        }

        if (TextUtils.isEmpty(mUpImageUri) || TextUtils.isEmpty(mUpUri)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastMake.showToast(getContext(), "上传失败,请从本地再次上传");
                }
            });

            System.out.println("上传网址读取失败");
            return;
        }

        //这里还可以对要上传的视频进行再次的加工
        //FileUtils.configProcessConfig(mp4SavedPath, builder);
        //这里可以设置Thumbnails类中的常量MINI_KIND和MICRO_KIND
        Bitmap bitmap = BitmapUtils.getVideoThumbnail(path, 1280, 720, MediaStore.Video.Thumbnails.MINI_KIND);
        if (bitmap == null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastMake.showToast(getContext(), "视频图片资源读取失败");
                }
            });

            return;
        }
        String bitmapPath = BitmapUtils.saveBitmap(bitmap);
        System.out.println("路径是" + bitmapPath);
        if (TextUtils.isEmpty(bitmapPath)) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastMake.showToast(getContext(), "视频图片资源保存失败");
                }
            });

            return;
        }
        System.out.println("mUpImageUri==" + mUpImageUri);
        System.out.println("mUpUri==" + mUpUri);
        File file = new File(bitmapPath);
        if (file == null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastMake.showToast(getContext(), "视频图片资源路径不存在");
                }
            });
            System.out.println("视频图片资源路径不存在");
            return;
        }
        //上传图片
        OkHttpUtils.post()//
                .addFile("file", "messenger_01.png", file)//
                .url(mUpImageUri)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "图片上传失败", Toast.LENGTH_SHORT).show();
                                System.out.println("图片上传失败");
                            }
                        });
                    }
                    @Override
                    public void onResponse(final String s, int i) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "上传成功", Toast.LENGTH_SHORT).show();
                                System.out.println("图片上传成功");
                                System.out.println(s);
                            }
                        });
                    }
                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                    }
                });
        //       //上传视频
        File mFile = new File(path);

        //设置进度条显示
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                //1.创建一个Dialog对象，如果是AlertDialog对象的话，弹出的自定义布局四周会有一些阴影，效果不好
                mProgressDialog = new Dialog(getContext());
                //去除标题栏
                mProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                //2.填充布局
                LayoutInflater inflater = LayoutInflater.from(getContext());
                View dialogView = inflater.inflate(R.layout.mo_uploadxinvideo_uploade_layout, null);
                mUpCompletedView=(CompletedView) dialogView.findViewById(R.id.upcompletedview);

                //将自定义布局设置进去
                mProgressDialog.setContentView(dialogView);
                //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                Window window = mProgressDialog.getWindow();
                lp.copyFrom(window.getAttributes());
                lp.width = 700;
                lp.height = 700;
                //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
                mProgressDialog.show();
                window.setAttributes(lp);
                //设置点击其它地方不让消失弹窗
                mProgressDialog.setCancelable(true);
                mUpCompletedView.setProgress(0);
            }
        });
        OkHttpUtils
                .post()//
                .addFile("file", "messenger_01.mp4", mFile)//
                .url(mUpUri)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "上传失败", Toast.LENGTH_SHORT).show();
                                System.out.println("视频上传失败");
                                mProgressDialog.hide();
                            }
                        });
                    }
                    @Override
                    public void onResponse(final String s, int i) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "上传成功", Toast.LENGTH_SHORT).show();
                                System.out.println(s);
                                System.out.println("视频上传成功");
                                mProgressDialog.hide();
                            }
                        });
                    }
                    @Override
                    public void inProgress(final float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        System.out.println("progress==" + (int) (100 * progress));
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                mUpCompletedView.setProgress((int) (100 * progress));
                            }
                        }).start();

                    }
                });
    }

}
